package com.nanshenycd.service.impl;

import com.nanshenycd.dao.UserDao;
import com.nanshenycd.pojo.User;
import com.nanshenycd.service.UserService;
import com.nanshenycd.util.CookieUtil;
import com.nanshenycd.util.UUIDUtil;
import com.nanshenycd.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;
import sun.security.krb5.internal.Ticket;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public User checkUser(String username, String password) {
        User user= userDao.findByUsernameAndPassword(username, password);
        return user;
    }

    @Override
    public User doLogin(LoginVo loginVo, HttpServletRequest request,HttpServletResponse response) {
        String username=loginVo.getUsername();
        String password=loginVo.getPassword();
        User user = userService.checkUser(username, password);
        if(user!=null){
            String ticket= UUIDUtil.uuid();
            user.setPassword(null);
            redisTemplate.opsForValue().set("user:"+ticket,user);
            //设置存储到session中
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }else{
            return null;
        }
        return user;
    }

    @Override
    public User getUserByCookie(String ticket, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(ticket)){
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + ticket);
        if(null!=null){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }
        return user;
    }

    @Override
    public boolean logout(User user, Ticket ticket) {
        return false;
    }
}
